const db = require("../db/index");
const bcrypt = require("bcryptjs");

// 获取用户信息
exports.getUser = (req, res) => {
    const selectUser =
        "select id,username,nickname,email,user_pic from ev_users where id=?";
    db.query(selectUser, req.user.id, (err, results) => {
        if (err) {
            res.mess(err);
        } else {
            if (results.length > 0) {
                res.send({
                    status: 200,
                    message: "获取成功！",
                    data: results[0],
                });
            } else {
                res.mess("没有查找到对应信息", 201);
            }
        }
    });
};
// 修改用户信息
exports.updateUser = (req, res) => {
    const updateUser = `update ev_users set ? where id=?`;
    db.query(updateUser, [req.body, req.body.id], (err, results) => {
        if (err) return res.mess(err);
        if (results.affectedRows !== 1) return res.mess("修改用户信息失败！");
        return res.mess("修改用户信息成功！", 200);
    });
};

// 修改密码
exports.updatePwd = (req, res) => {
    const sql = `select * from ev_users where id=?`;
    // 判断用户是否存在
    db.query(sql, req.user.id, (err, results) => {
        if (err) return res.mess(err);
        if (results.length !== 1) return res.mess("用户不存在!");
        // 判断提价密码与旧密码是否一致
        const compareRes = bcrypt.compareSync(
            req.body.oldPassword,
            results[0].password
        );
        if (!compareRes) {
            return res.mess("旧密码错误！");
        } else {
            const updatePwd = `update ev_users set password=? where id=?`;
            const newPwd = bcrypt.hashSync(req.body.newPassword, 10);
            // 修改密码
            db.query(updatePwd, [newPwd, req.user.id], (err, results) => {
                if (err) return res.mess(err);
                if (results.affectedRows !== 1) {
                    return res.mess("修改密码失败！");
                } else {
                    return res.mess("修改密码成功！", 200);
                }
            });
        }
    });
};

// 修改头像
exports.updateHeadPic = (req, res) => {
    const sql = `update ev_users set user_pic=? where id=?`;
    db.query(sql, [req.body.headPic, req.user.id], (err, results) => {
        if (err) return res.mess(err);
        if (results.affectedRows !== 1) {
            return res.mess("修改头像失败！");
        } else {
            return res.mess("修改头像成功！", 200);
        }
    });
};